﻿#include "iostream"
#include "GlobalMsg.h"


//TCP客户接入
void OnTcpConnect()
{
    //static uint32_t tempConnectIndex = 0;

    //这里的循环表示可能多个客户端接入，防止遗漏造成堵塞
    while(serverMsg::Server_TCP->hasPendingConnections()){
        QTcpSocket * tSocket = serverMsg::Server_TCP->nextPendingConnection();

        //判断临时用户长度是否超额，超额则断开
        if(serverMsg::connectList_temp.length() >= serverMsg::UserTempNum){
            serverMsg::Server_TCP->disconnect(tSocket); //断开链接
            break;
        }

        //输出TCP临时链接
        //std::cout<<"TCP Connect ->" <<  tSocket->peerAddress().toString().toStdString() <<":"<<tSocket->peerPort() <<std::endl;

        //连接数据
        QAbstractSocket::connect(tSocket,&QTcpSocket::readyRead,[=](){
            OnTcpReadyRead(tSocket);
        }); //链接收到数据

        QAbstractSocket::connect(tSocket,&QTcpSocket::disconnected,[=](){
            OnTcpDisConnect(tSocket);
        }); //链接断开连接



        //添加临时信息到
        clientMsg t_clientMsg;
        t_clientMsg.tcp_Socket = tSocket; //零时记录TcpSocket，若验证通过则加入到长连接
        t_clientMsg.time_connect = QDateTime::currentDateTime();
        t_clientMsg.passwdId = tSocket->peerPort();
        serverMsg::connectList_temp.append(t_clientMsg);


        //返回端口数据,进行数据验证
        QByteArray t_data;
        t_data.append({'\1'}); //添加类型信息，返回TCP端口信息
        t_data.append(QByteArray::number(t_clientMsg.passwdId));  //添加端口信息
        tSocket->write(t_data); //发送返回的
    }
}

//服务器TCP收到数据
void OnTcpReadyRead(QTcpSocket * tSocket)
{



    QByteArray t_data = tSocket->readAll();
    //std::cout << t_data.toStdString()<<std::endl;

//    for(int a=0;a<t_data.length();a++){
//        qDebug() << t_data.at(a) << "   " << t_data.length();
//    }


    if(t_data.at(0) == '\0'){ //呼吸包
        return;
    }
    else if(t_data.at(0) == '\1'){ //链接请求
        QByteArray t_sendData;
        int t_friendID= t_data.right(t_data.length() - 1).toInt(); //对方ID
        if(t_friendID == tSocket->peerPort()){ //判断是否为自己，自己不能够传输给自己
            t_sendData.append('\4');
            t_sendData.append(QByteArray::number(t_friendID));
            tSocket->write(t_sendData);
            return;
        }


        for(int a=0;a<connectList.length();a++){
            if(connectList[a].TcpSocket->peerPort() == t_friendID){
                t_sendData.append('\5'); //请求连接
                t_sendData.append(QByteArray::number(tSocket->peerPort()));
                connectList[a].TcpSocket->write(t_sendData); //转发连接请求
                return;
            }
        }


        //不存在这个链接,返回无效连接
        t_sendData.append('\3');
        t_sendData.append(QByteArray::number(t_friendID));
        tSocket->write(t_sendData);
    }
    else if(t_data.at(0) == '\3'){ //连接被拒绝
        int t_friendID= t_data.right(t_data.length() - 1).toInt(); //对方ID
        for(int a=0;a<connectList.length();a++){
            if(connectList[a].TcpSocket->peerPort() == t_friendID){
                QByteArray t_sendData;
                t_sendData.append('\4'); //返回源发送方拒绝通知
                t_sendData.append(QByteArray::number(tSocket->peerPort()));
                connectList[a].TcpSocket->write(t_sendData); //返回拒绝请求
                return;
            }
        }
    }
    else if(t_data.at(0) == '\4'){ //允许连接，开始配对
        int t_friendID= t_data.right(t_data.length() - 1).toInt(); //对方ID
        netConnect * t_connect1 = nullptr;  //发送端的信息
        netConnect * t_connect2 = nullptr;  //接收端的信息
        QByteArray t_sendData;

        for(int a=0;a<connectList.length();a++){
            if(connectList[a].TcpSocket->peerPort() == t_friendID){
                t_connect1 = &connectList[a];
            }
            else if(connectList[a].TcpSocket == tSocket){
                t_connect2 = &connectList[a];
            }
        }

        //检索是否都在线
        if(t_connect1 == nullptr || t_connect2 == nullptr){
            t_sendData.append('\4');
            t_sendData.append(QByteArray::number(t_friendID));
            tSocket->write(t_sendData); //返回忙碌，无法创建连接
            return;
        }

        //开始交换UDP数据
        QString t_user1 = getIpMsgStr(t_connect1->UDP_Ip,t_connect1->UDP_Port,t_connect1->TcpSocket->peerPort());
        QString t_user2 = getIpMsgStr(t_connect2->UDP_Ip,t_connect2->UDP_Port,t_connect2->TcpSocket->peerPort());

        t_sendData.clear();
        t_sendData.append('\6');
        t_sendData.append(t_user1.toLocal8Bit());
        t_connect2->TcpSocket->write(t_sendData); //把1的UDP发给2

        t_sendData.clear();
        t_sendData.append('\6');
        t_sendData.append(t_user2.toLocal8Bit());
        t_connect1->TcpSocket->write(t_sendData); //把2的UDP发给1
    }
    else if(t_data.at(0) == '\5'){ //取消或者关闭连接
        QString t_str = QString::fromUtf8(t_data.right(t_data.length() - 1));
        QStringList t_strList = t_str.split(':');
        if(t_strList.length() != 2) return;
        int t_user1 = t_strList[0].toInt();
        int t_user2 = t_strList[1].toInt();
        for(int a=0;a<connectList.length();a++){
            if(connectList[a].TcpSocket->peerPort() == t_user1 || connectList[a].TcpSocket->peerPort() == t_user2 ){
                QByteArray t_sendData;
                t_sendData.append('\7'); //取消连接的消息
                connectList[a].TcpSocket->write(t_sendData);
            }
        }

    }
    else if(t_data.at(0) == '\6'){ //传输完成
        QString t_str = QString::fromUtf8(t_data.right(t_data.length() - 1));
        QStringList t_strList = t_str.split(':');
        if(t_strList.length() != 2) return;
        int t_user1 = t_strList[0].toInt();
        int t_user2 = t_strList[1].toInt();
        for(int a=0;a<connectList.length();a++){
            if(connectList[a].TcpSocket->peerPort() == t_user1 || connectList[a].TcpSocket->peerPort() == t_user2 ){
                QByteArray t_sendData;
                t_sendData.append('\8'); //完成传输的消息
                connectList[a].TcpSocket->write(t_sendData);
            }
        }
    }

}

//断开连接
void OnTcpDisConnect(QTcpSocket * tSocket)
{
    //std::cout<<"TCP DisConnect ->" <<  tSocket->peerAddress().toString().toStdString() <<":"<<tSocket->peerPort() <<std::endl;//断开连接
    //删除常驻信息
    for(QList<clientMsg>::iterator i = serverMsg::connectList_temp.begin(); i<serverMsg::connectList_temp.end(); i++){
        if((*i).tcp_Socket == tSocket){
            serverMsg::connectList_temp.erase(i);
            break;
        }
    }
}
